function handles = mapAvgFromCellListB(handles, figFlag)
% mapAvgFromCellListB
%
% Editing:
% gs may 2005 -- adapted for mapAverager1p0
%   from previous version of mapAvgFromCellList
% --------------------------------------------------------------------

% From older function: Options to re-align maps according to soma or barrel coordinates:
%   - 'none'
%   - 'alignBySliceXY'
%   - 'alignBySomaXY'
%   - 'alignBySomaXSliceY'
% --------------------------------------------------------------------

% get list of names of cells/expts
listOfCells = get(handles.cellList, 'String');

% alignment options
alignOptions = 'alignBySliceXY';
%     alignOptions = 'alignBySomaXY';
%     alignOptions = 'alignBySomaXSliceY';
% TODO: incorporate these options into the gui

% type of map to analyze
handles = getMapStr(handles);
mapStr = handles.analysis.mapAverager.mapType;

% main loading loop
numCells = size(listOfCells, 1);
for n = 1:numCells
    try
        % load the cells' data
        cellA = eval([listOfCells{n}]);     % load the cell/expt data
        mapSpacing(n) = cellA.mapSpacing;   % map spacing
        try
            cellType{n} = cellA.cellType;       % cell type
        catch
            cellType{n} = 'neuron';
        end

        if isfield(cellA, 'xyNew')
            XY(:,:,n) = [cellA.xyNew(1) cellA.xyNew(2) * (-1)];           % soma XY position
        else
            XY(:,:,n) = cellA.xy;               % soma XY position
        end

        try
            Z(n) = cellA.z;                     % soma Z position (depth in slice)
        catch
            Z(n) = NaN;
        end

        try
            barrelXY(:,:,n) = cellA.barrelXY;   % barrel XY position
        catch
        end

        eval(['map = ' mapStr]);
        %     map = cellA.genMean;                % cell's genMean map
        M(:,:,n) = map;

        % re-orient if necessary
        try
            if strcmp(cellA.orientation, 'upside down') % Y values need to change sign
                %         XY(:,2,n) = -XY(:,2,n);
                %         barrelXY(:,2,n) = -barrelXY(:,2,n);
                M(:,:,n) = flipud(map);
            end
        catch
        end
    catch
        disp(['Problem with data for cell ' num2str(n) ', ' cellA.experiment]);
    end
end

% some tidying up etc
maps = M;
maps(isnan(maps)) = inf;
XY = squeeze(XY)';
try
    barrelXY = squeeze(barrelXY)';
catch
end
% X = XY(:,1) + barrelXY(:,1);
X = XY(:,1);
Y = XY(:,2);

% distance scale
if numel(unique(mapSpacing)) ~= 1
    beep;
    disp('Error in mapAvgFromCellList: map spacing apparently varies across cells.')
    return
else
    [r,c] = size(maps(:,:,1));
    dx = unique(mapSpacing);
    xdata = [0:dx:(r-1)*dx] - (r-1)*dx/2;
    ydata = xdata;
end

% shift maps to align to barrel/septal grid
try
    switch alignOptions
        case 'none'
        case 'alignBySliceXY'
            for n = 1:numCells
                newmap(:,:,n) = cellShifter(maps(:,:,n), barrelXY(n,:), dx);
                X(n) = X(n) - barrelXY(n,1);
                Y(n) = Y(n) - barrelXY(n,2);
            end
            maps = newmap((1+r/2):(r+r/2),(1+c/2):(c+c/2),:);
            maps(isnan(maps)) = inf;
        case 'alignBySomaXY'
            for n = 1:numCells
                newmap(:,:,n) = cellShifter(maps(:,:,n), XY(n,:), dx);
                X(n) = X(n) - XY(n,1);
                Y(n) = Y(n) - XY(n,2);
            end
            maps = newmap((1+r/2):(r+r/2),(1+c/2):(c+c/2),:);
            maps(isnan(maps)) = inf;
        case 'alignBySomaXSliceY'
            for n = 1:numCells
                newmap(:,:,n) = cellShifter(maps(:,:,n), [XY(n,1) barrelXY(n,2)], dx);
                X(n) = X(n) - XY(n,1);
                Y(n) = Y(n) - barrelXY(n,2);
            end
            maps = newmap((1+r/2):(r+r/2),(1+c/2):(c+c/2),:);
            maps(isnan(maps)) = inf;
    end
catch
end
maps(isnan(maps)) = inf;

% average map
maps(maps==inf) = NaN;
avgMap = mapAverage(maps, 1);
avgMap(isnan(avgMap)) = inf;
maps(isnan(maps)) = inf;

% output:
handles.analysis.mapAverager.avgMap = avgMap;
handles.analysis.mapAverager.mapStack = maps;
handles.analysis.mapAverager.xdata = xdata;
handles.analysis.mapAverager.ydata = ydata;
handles.analysis.mapAverager.somaX = XY(:,1);
handles.analysis.mapAverager.somaY = XY(:,2);
handles.analysis.mapAverager.somaZ = Z;

if figFlag
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % FIGURE
    hfig = figure;
    set(hfig, 'Color', 'w', 'Units', 'normalized', ...
        'Position', [0.0089    0.6442    0.5385    0.2875], 'DoubleBuffer', 'on');
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % plot of average map
    hax(1) = subplot(1,2,1);
    himg = imagesc(avgMap);
    set(himg, 'XData', xdata, 'YData', ydata);
    set(hax, 'XLim', [min(xdata)-dx/2 max(xdata)+dx/2], 'YLim', [min(ydata)-dx/2 max(ydata)+dx/2])
    pbaspect([1 1 1]);
    colormap(flipud(colormap(jet2)));
    title(['Average map (N=' num2str(numCells) ')'])
    
    % store map data
    set(himg, 'UserData', maps);
    % pixel/interpolate option via uicontextmenu
    cmenu = uicontextmenu;
    set(himg, 'UIContextMenu', cmenu);
    % cb1 = ['pix2interp'];
    item1 = uimenu(cmenu, 'Label', 'activate pix/interp options', 'Callback', 'pix2interp');
    interpRedOutForAvg(himg, 1);
    
    
    % plot the soma positions 
    hold on;
    for n = 1:numel(X)
        if strcmp(cellType{n}, 'pyramidal') | strcmp(cellType{n}, 'pyramid')
            marker = '^';
        elseif strcmp(cellType{n}, 'stellate')
            marker = 'pentagram';
        elseif strcmp(cellType{n}, 'interneuron')
            marker = 'o';
        else
            marker = 'square';
        end
        hplt(n) = plot(X(n), Y(n), 'k^');
        set(hplt(n), 'Marker', marker, 'MarkerEdgeColor', 'k', 'MarkerFaceColor', 'w', 'MarkerSize', 6);
    end
    
    pos = get(gca, 'Position');
    set(gca, 'Position', [pos(1) pos(2) pos(3) pos(4)*.9]);

    titleString = handles.analysis.mapAverager.currentGroup;
    ht = text(0, 0, titleString);
    set(ht, 'Units', 'normalized', 'Position', [-.2 1.1 0], ...
        'FontSize', 11, 'FontWeight', 'bold', ...
        'Interpreter', 'none'); 
    % 20070226GS: set interpreter to none to avoid underscore display problem
    
    ht = text(0, 0, 'R-click on map for interpolation options');
    set(ht, 'Units', 'normalized', 'Position', [-.2 -.1 0]);
    
    colorbar;
    hold off;
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % plot of individual maps
    mapN = 1;
    hax(2) = subplot(1,2,2);
    himg(2) = imagesc(maps(:,:,mapN));
    set(himg(2), 'XData', xdata, 'YData', ydata);
    set(hax, 'XLim', [min(xdata)-dx/2 max(xdata)+dx/2], 'YLim', [min(ydata)-dx/2 max(ydata)+dx/2])
    pbaspect([1 1 1]);
    
    % store map and soma data
    data.maps = maps;
    data.X = X;
    data.Y = Y;
    data.cellType = cellType;
    data.cellNames = listOfCells;
    % data.cellNames = filename;
    data.currentNum = 1;
    set(himg(2), 'UserData', data);
    
    % page through maps option via ButtonDownFcn
    set(himg(2), 'ButtonDownFcn', 'pageThroughMaps(gco)');
    
    % title(data.cellNames(data.currentNum, :));
    title(data.cellNames{data.currentNum});
    
    % plot the soma position
    hold on;
    n = mapN;
    if strcmp(cellType{n}, 'pyramidal') | strcmp(cellType{n}, 'pyramid')
        marker = '^';
    elseif strcmp(cellType{n}, 'stellate')
        marker = 'pentagram';
    elseif strcmp(cellType{n}, 'interneuron')
        marker = 'o';
    else
        marker = 'square';
    end
    hplt(n) = plot(X(n), Y(n), 'k^');
    set(hplt(n), 'Marker', marker, 'MarkerEdgeColor', 'k', ...
        'MarkerFaceColor', 'w', 'MarkerSize', 6, 'Tag', 'soma marker');
    
    % OPTION to turn on pixvals for measuring distances
    % pixvals on
    % pixvals off
    pos = get(gca, 'Position');
    set(gca, 'Position', [pos(1) pos(2) pos(3) pos(4)*.9]);
    
    colorbar;
    hold off;
    
end